﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO.Ports;

namespace KeystrokeConverter
{
    public class CommandManager
    {
        private SerialPort _port;
        private byte[] _writeBuffer;
        private byte[] _readBuffer;

        private System.Threading.Timer _readTimer;

        private static int WRITE_SIZE = 1;
        private static int READ_SIZE = 2;

        private ArduinoStatus _status;


        public CommandManager()
        {
            ComConfig config = ComConfig.Instance;
            _writeBuffer = new byte[WRITE_SIZE];
            _readBuffer = new byte[READ_SIZE];
            _port = new SerialPort(config.PortName, config.BaudRate,config.PortParity,8,StopBits.One);
            _port.ReadTimeout = 10;
            _readTimer = new System.Threading.Timer(TryReceive);
        }

        public bool OpenConnection()
        {
            try
            {
                _port.Open();
                //_readTimer.Change(20, 20); 
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool CloseConnection()
        {
            try
            {
                _readTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                _port.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool SendCommand(byte command)
        {
            if (_port.IsOpen)
            {
                byte[] toSend = new byte[1];
                toSend[0] = command;
                _port.Write(toSend, 0, WRITE_SIZE);
                return true;
            }
            else return false;
        }

        private void TryReceive(object sender)
        {
            try
            {
                Console.WriteLine(_port.ReadExisting());
                //_port.Read(_readBuffer, 0, READ_SIZE);
            }
            catch
            {
                return;
            }
            /*byte irByte = _readBuffer[1];
            byte cmdByte = _readBuffer[0];

            if (cmdByte == AvailableCommands.cmdFwd)
                Console.WriteLine("Moving Forward!");

            foreach (byte b in _readBuffer)
            {
                Console.Write("{0}\t", b);
            }
            Console.WriteLine();*/
        }
    }



    public class AvailableCommands
    {
        public static byte cmdStop = 0x40;
        public static byte cmdFwd = 0x60;
        public static byte cmdback = 0x68;
        public static byte cmdLeft = 0x70;
        public static byte cmdRight = 0x78;
        public static byte cmdRaise = 0x64;
        public static byte cmdLower = 0x6C;
    }
}
